<!--
 * @Descripttion: 说明
 * @version: V1.0
 * @Author: aqiang
 * @Date: 2024-03-05 01:52:31
 * @LastEditTime: 2024-09-13 10:15:33
-->

<template>
		<el-drawer v-model="visible" :title="!dataForm.id ? '新增档口收货' : '修改档口收货'" :close-on-click-modal="false" :size="1400">
			<div v-loading="dataListLoading">
				<el-form ref="dataFormRef" label-position="top" :model="dataForm" :rules="dataRules" label-width="20px">
					<el-tabs type="border-card">
						<el-tab-pane label="基本资料">
							<el-row class="form-row">
								<el-col :span="5" v-if="isUpdate">
									<el-form-item prop="field1" label="收据单号">
										<div class="flex-container" prop="collectNo">
											<el-input v-model="dataForm.collectNo" class="input-width" type="text"
												readonly></el-input>
											
										</div>
									</el-form-item>
								</el-col>

								<el-col :span="5">
									<el-form-item label="是否问题件" prop="questionState">
										<el-radio-group v-model="dataForm.questionState">
											<el-radio :label="1">否</el-radio>
											<el-radio :label="2">是</el-radio>
										</el-radio-group>
									</el-form-item>
								</el-col>

								<el-col :span="5">
									<el-form-item prop="customId" label="客户">
										<el-select v-model="dataForm.customId" filterable clearable placeholder="客户"
											@change="updateCsId">
											<el-option v-for="item in customerOptions" :key="item.value"
												:label="item.customName" :value="item.customId" />
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="20">
								<el-col :span="5">
									<el-form-item prop="operateId" label="操作">
										<el-select v-model="dataForm.operateId" remote filterable disabled>
											<el-option v-for="item in operateIdOptions" :key="item.value"
												:label="item.label" :value="item.value" />
										</el-select>
									</el-form-item>
								</el-col>

								<el-col :span="5">
									<el-form-item prop="salesId" label="业务员">
										<el-select v-model="dataForm.salesId" remote filterable disabled>
											<el-option v-for="item in customerOptions" :key="item.value"
												:label="item.saName" :value="item.saId" />
										</el-select>
									</el-form-item>
								</el-col>

								<el-col :span="5">
									<el-form-item prop="businessId" label="客服">
										<el-select v-model="dataForm.businessId" remote filterable disabled>
											<el-option v-for="item in customerOptions" :key="item.value"
												:label="item.csName" :value="item.csId" />
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="20">
								<el-col :span="5">
									<el-form-item prop="payState" label="付款方式">
										<el-select v-model="dataForm.payState">
											<el-option v-for="item in paysOptions" :key="item.value" :label="item.label"
												:value="item.value" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item prop="businessState" label="业务类型">
										<el-select v-model="dataForm.businessState">
											<el-option v-for="item in businessTypeList" :key="item.value"
												:label="item.label" :value="item.value" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item prop="collectTime" label="收货日期">
										<el-date-picker v-model="dataForm.collectTime" type="datetime"
											placeholder="请选择收获日期" />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="20">
								<el-col :span="5">
									<el-form-item prop="sendor" label="发货人">
										<el-input v-model="dataForm.sendor"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item prop="sendorPhone" label="发货人电话">
										<el-input v-model="dataForm.sendorPhone"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item prop="sendAddress" label="发货人地址">
										<el-input v-model="dataForm.sendAddress"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item prop="field3" label="快递单号">
										<el-input v-model="dataForm.expressNo" type="textarea"
											placeholder="请输入快递单号，每行一个"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="20">
								<el-col :span="5">
									<el-form-item prop="collector" label="收货人">
										<el-input v-model="dataForm.collector"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item prop="collectorPhone" label="收货人电话">
										<el-input v-model="dataForm.collectorPhone"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item prop="collectAddress" label="收货人地址">
										<el-input v-model="dataForm.collectAddress"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="20">
								<el-col :span="4">
									<el-form-item prop="arrivalState" label="到货方式">
										<el-select v-model="dataForm.arrivalState">
											<el-option v-for="item in arrivalOptions" :key="item.value"
												:label="item.label" :value="item.value" />
										</el-select>
									</el-form-item>
								</el-col>

								<el-col :span="5">
									<el-form-item prop="originCountry" label="始发地国家">
										<div class="flex-container">
											<el-select v-model="dataForm.originCountry">
												<el-option v-for="item in countryList" :key="item.value"
													:label="item.label" :value="item.value" />
											</el-select>
										</div>
									</el-form-item>
								</el-col>
								<el-col :span="5">
									<el-form-item prop="destinationCountry" label="目的地国家">
										<div class="flex-container">
											<el-select v-model="dataForm.destinationCountry">
												<el-option v-for="item in countryList" :key="item.value"
													:label="item.label" :value="item.value" />
											</el-select>
										</div>
									</el-form-item>
								</el-col>
							</el-row>
						</el-tab-pane>
						<el-tab-pane label="货物信息">
							<el-row justify="space-between">
								<el-col :span="4">
									<el-form-item prop="collectNum" label="收到件数">
										<el-input v-model="dataForm.collectNum" class="input-width"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="6">
									<el-form-item prop="collectTrueNum" label="实际件数">
										<el-input v-model="dataForm.collectTrueNum" placeholder="请实际件数"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="6">
									<el-form-item prop="weight" label="重量(kg)">
										<el-input v-model="dataForm.weight" disabled></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="6">
									<el-form-item prop="tiji" label="体积(m³)">
										<el-input v-model="dataForm.tiji" disabled></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="4">
									<el-form-item prop="tijiWeight" label="体积重(Kg)">
										<el-input v-model="dataForm.tijiWeight" disabled class="input-width"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="4">
									<el-form-item prop="chargeState" label="计费重类型">
										<el-select v-model="dataForm.chargeState">
											<el-option v-for="item in chargedOptions" :key="item.value"
												:label="item.label" :value="item.value" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="4">
									<el-form-item prop="chargedWeight" label="计费重量">
										<el-input v-model="dataForm.chargedWeight"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-table v-loading="dataLoading" :data="dataForm.smallVOList" border style="width: 100%">
								<el-table-column v-if="isUpdate" label="货编号" header-align="center" align="center">
									<template #default="scope">
										<el-input v-model="scope.row.collectNo" disabled> </el-input>
									</template>
								</el-table-column>
								<el-table-column prop="collectState" label="状态" header-align="center" align="center">
									<template #default="scope">
										<el-select v-if="scope.row.collectState <= 1" v-model="scope.row.collectState">
											<el-option v-for="item in cargoOptionsCanUpdate" :key="item.value"
												:label="item.label" :value="item.value" />
										</el-select>

										<div v-if="scope.row.collectState > 1">{{collectStateArr[scope.row.collectState]}}</div>

									</template>
								</el-table-column>
								<el-table-column prop="collectName" label="货名" header-align="center" align="center">
									<template #default="scope">
										<el-input v-model="scope.row.collectName"> </el-input>
									</template>
								</el-table-column>
								<el-table-column prop="collectType" label="货物类型" header-align="center" align="center">
									<template #default="scope">
										<el-select v-model="scope.row.collectType">
											<el-option v-for="item in collectTypeOptions" :key="item.value"
												:label="item.label" :value="item.value" />
										</el-select>
									</template>
								</el-table-column>
								<el-table-column prop="collectLength" label="单个长(cm)" header-align="center"
									align="center">
									<template #default="{ row }">
										<el-input v-model="row.collectLength" @input="collectTJi(row)"> </el-input>
									</template>
								</el-table-column>
								<el-table-column prop="collectKuan" label="单个宽(cm)" header-align="center"
									align="center">
									<template #default="{ row }">
										<el-input v-model="row.collectKuan" @input="collectTJi(row)"> </el-input>
									</template>
								</el-table-column>
								<el-table-column prop="collectHeight" label="单个高(cm)" header-align="center"
									align="center">
									<template #default="{ row }">
										<el-input v-model="row.collectHeight" @input="collectTJi(row)"> </el-input>
									</template>
								</el-table-column>

								<el-table-column label="NC" header-align="center" align="center">
									<template #default="scope">
										<el-select v-model="scope.row.nc" remote filterable clearable
											placeholder="请选择NC">
											<el-option v-for="item in NCOptions" :key="item.value" :label="item.label"
												:value="item.value" />
										</el-select>
									</template>
								</el-table-column>
								<el-table-column label="单个重(kg)" header-align="center" align="center">
									<template #default="{ row }">
										<el-input v-model="row.collectWeight"> </el-input>
									</template>
								</el-table-column>
								<el-table-column label="单个体积(m³)" header-align="center" align="center">
									<template #default="{ row }">
										<el-input v-model="row.collectTiji"> </el-input>
									</template>
								</el-table-column>
								<el-table-column label="单个体积重(m³)" header-align="center" align="center">
									<template #default="scope">
										<el-input v-model="scope.row.collectTijiWeight"> </el-input>
									</template>
								</el-table-column>
								<el-table-column prop="dictType" label="操作" header-align="center" align="center">
									<template #default="scope">
										<el-button @click="deleteHandle(scope.$index)">
											<el-icon>
												<Delete />
											</el-icon>
										</el-button>
									</template>
								</el-table-column>
							</el-table>
							<div style="display: flex; justify-content: center">
								<el-button style="margin-top: 10px" type="primary" @click="addHandle()">
									<el-icon>
										<Plus />
									</el-icon>
									新增
								</el-button>
							</div>
						</el-tab-pane>
					</el-tabs>
				</el-form>
			</div>

			<template #footer>
				<el-button @click="closeDrawer">取消</el-button>
				<el-button type="primary" @click="submitHandle(dataFormRef)">确定</el-button>
			</template>
		</el-drawer>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { QuestionFilled, Plus, Delete } from '@element-plus/icons-vue'
import { fetchWarning, myError } from '@/store/modules/common'
import type { FormInstance, FormRules } from 'element-plus'
import { freightData, ElSelectOption } from '../../../components/type/general'
import {
	collectExpressAddApi,
	getIdApi,
	collectExpressSelectSmallApi,
	collectExpressUpdateApi,
	getExpressRelatedData
} from '@/api/freight'
import { ElMessage } from 'element-plus/es'
import { getDataDictionary, useDictTypeAllApi } from '@/api/dict'

const props = defineProps({
	isUpdate: {
		type: Boolean
	}
})

const emit = defineEmits(['refreshDataList'])

const visible = defineModel<boolean>('visible')
const initState = {
	id: '',
	questionState: 1,
	collectNo: '',
	ordersNo: '',
	expressNo: '',
	collectState: '',
	origin: '',
	dest: '',
	businessState: '',
	collectorPhone: '',
	sendor: '',
	collector: '',
	payState: '',
	collectNum: '',
	weight: '',
	chargedWeight: '',
	custom: '',
	business: '',
	goodsHourse: '',
	collectTime: '',
	arrivalstate: '',
	address: '',
	paystate: '',
	sendorPhone: '',
	arrivalState: '',
	customId: '',
	businessId: '',
	saId: '',
	sendAddress: '',
	collectAddress: '',
	salesId: '',
	collectTrueNum: '',
	collectType: '',
	chargeState: '',
	tiji: '',
	tijiWeight: '',
	operateId: '',
	originCountry: '',
	destinationCountry: '',
	// 多个小包裹
	smallVOList: <any> []
}
const dataForm = reactive({ ...initState })

const dataListLoading = ref(false)
const customerOptions = ref<ElSelectOption[]>([])


const dataLoading = ref(false)

//支付方式等

const NCOptions = ref<ElSelectOption[]>([])

//业务类型
const businessTypeList = ref<ElSelectOption[]>([])

const chargedOptions = ref<ElSelectOption[]>([])
const collectTypeOptions = ref<ElSelectOption[]>([])

let collectStateArr = new Array(); 
const cargoOptionsCanUpdate = ref<ElSelectOption[]>([])

const dataRules: FormRules = reactive({
	collectNo: [{ required: true, message: '请输入收据单号', trigger: 'blur' }],
	ordersNo: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
	expressNo: [{ required: true, message: '请输入快递单号	', trigger: 'blur' }],
	businessState: [{ required: true, message: '选择业务类型', trigger: 'change' }],
	sendor: [{ required: false, message: '请输入发货人', trigger: 'blur' }],
	collector: [{ required: true, message: '请输入收货人', trigger: 'blur' }],
	collectNum: [{ required: true, message: '请输入收货件数', trigger: 'blur' }],
	weight: [{ required: true, message: '请输入重量', trigger: 'blur' }],
	chargedWeight: [{ required: true, message: '请输入计费重量', trigger: 'blur' }],
	customId: [{ required: true, message: '请选择客户', trigger: 'change' }],
	businessId: [{ required: true, message: '请选择客服', trigger: 'change' }],
	operateId: [{ required: true, message: '请选择操作人', trigger: 'change' }],
	salesId: [{ required: true, message: '请选择业务员', trigger: 'change' }],
	originCountry: [{ required: true, message: '请选择始发地国家', trigger: 'change' }],
	destinationCountry: [{ required: true, message: '请选择目的地国家', trigger: 'change' }],
	collectTime: [{ required: true, message: '请选择收货日期', trigger: 'change' }],
	sendorPhone: [{ required: false, message: '请输入发货人电话', trigger: 'blur' }],
	collectorPhone: [{ required: true, message: '请输入收货人电话	', trigger: 'blur' }],
	questionState: [{ required: true, message: '请选择件状态', trigger: 'change' }],
	payState: [{ required: true, message: '请选择付款方式', trigger: 'change' }],
	arrivalState: [{ required: true, message: '请选择到货方式', trigger: 'change' }],
	sendAddress: [{ required: false, message: '请输入地址', trigger: 'blur' }],
	chargeState: [{ required: true, message: '请选择计费重类型', trigger: 'change' }],
	collectTrueNum: [{ required: true, message: '请输入实际件数', trigger: 'blur' }],
	collectType: [{ required: true, message: '请选择货物类型', trigger: 'change' }],
	tiji: [{ required: true, message: '请输入体积', trigger: 'blur' }],
	tijiWeight: [{ required: true, message: '请输入体积重', trigger: 'blur' }],
	collectAddress: [{ required: false, message: '请输入收货人地址', trigger: 'blur' }]
})

function formatDateString(dateString: string): string {
	const date = new Date(dateString)

	if (isNaN(date.getTime())) {
		// 处理无效日期
		return 'Invalid Date'
	}

	const year = date.getFullYear()
	const month = padZero(date.getMonth() + 1)
	const day = padZero(date.getDate())
	const hours = padZero(date.getHours())
	const minutes = padZero(date.getMinutes())
	const seconds = padZero(date.getSeconds())

	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
function padZero(value: number): string {
	return value < 10 ? `0${value}` : `${value}`
}


//重置表单
// const resetForm = () => {
// 	Object.assign(dataForm, { ...initState })
// }
//取消
const closeDrawer = () => {
	visible.value = false
	// resetForm()
}
// 提交
const dataFormRef = ref(null)
const submitHandle =  (formEl: any) => {
	formEl.validate( (valid: any) => {
		if (!valid) {
			return false
		}

		const obj = {}
		const params = { ...dataForm, ...obj }
		console.log('参数', params)

		if (dataForm.collectTime !== '') {
			params.collectTime = formatDateString(dataForm.collectTime)
		}
		if (params.expressNo) {
			params.expressNo = params.expressNo.replace(/[\s\n\r]+/g, ',')
		}
		if(dataForm.id){
			collectExpressUpdateApi(params).then(() => {
				ElMessage.success({
					message: '操作成功',
					duration: 500,
					onClose: () => {
						visible.value = false
						emit('refreshDataList')
					}
				})
			})
		}else{
			collectExpressAddApi(params).then(() => {
				ElMessage.success({
					message: '操作成功',
					duration: 500,
					onClose: () => {
						visible.value = false
						emit('refreshDataList')
					}
				})
			})
		}
		

		
			
	})
}

const operateIdOptions = ref<ElSelectOption[]>([])

// 获取操作客户等
async function getId() {
	try {
		const res = await getIdApi()

		if (fetchWarning(res)) {
			return
		}
		let data = res.data || []
		// console.log('客户', data)
		customerOptions.value = data.list
		dataForm.operateId = data.operateId
		initState.operateId = data.operateId
		operateIdOptions.value.push({
			label: data.operateName,
			value: data.operateId
		})
	} catch (e) {
		myError(e)
	}
}

const getDictionary = async (params: { dictType: string }) => {
	try {
		const res = await getDataDictionary(params)

		if (fetchWarning(res)) {
			return
		}
		let data = res.data || []
		console.log('字典数据', data)
		data.forEach((item: { dictType: any; dictLabel: any; id: string | number; dictValue: string | number }) => {
			switch (item.dictType) {
				case 'NC':
					NCOptions.value.push({ label: item.dictLabel, value: item.dictValue })
					break
				default:
					console.warn('未知字典类型:', item.dictType)
			}
		})
		
	} catch (error) {
		console.error('获取字典失败', error)
	}
}
const initDic = () => {
	getDictionary({
		dictType: 'NC'
	})
}
initDic()

//选择客户自动选择客服和收货人
const updateCsId = () => {
	const selectedCustomer = customerOptions.value.find(opt => opt.customId === dataForm.customId)

	if (selectedCustomer) {
		dataForm.businessId = selectedCustomer.csId
		dataForm.salesId = selectedCustomer.saId
		console.log(selectedCustomer, 'selectedCustomer')
		dataForm.collectorPhone = selectedCustomer.customPhone
		// dataForm.collectAddress
		dataForm.collector = selectedCustomer.customName
	}
}


// 父组件控制
const init = (val?: object) => {
	dataListLoading.value = true
	for (const key in initState) {
		if (Object.prototype.hasOwnProperty.call(dataForm, key)) {
			dataForm[key] = initState[key]
		}
	}

	if ('update' == val.type) {
		// dataForm.collectNo =val
		collectExpressSelectSmallApi({ id: val.id }).then(res => {
			if (res.data) {
				dataForm.smallVOList = res.data
			}
		})
		Object.keys(val).forEach(key => {
			if (dataForm.hasOwnProperty(key)) {
				dataForm[key] = val[key]
			}
		})
		// console.log(val, '2222222222', dataForm)
	} 
	visible.value = true
	dataListLoading.value = false
}
// 新增条数
const addHandle = () => {
	dataForm.smallVOList.push({ collectName : "",collectState : 0});
}
const deleteHandle = (index?: number) => {
	dataForm.smallVOList.splice(index, 1)
}
// 总重量
watch(
	() => dataForm.smallVOList,
	val => {
		if (Array.isArray(val)) {
			dataForm.weight = val.reduce((total, item) => {
				return total + parseFloat(item.collectWeight || 0)
			}, 0)
		} else {
			// 如果 smallVOList 不是数组，则将 weight 设置为 0 或其他默认值
			dataForm.weight = 0
		}
	},
	{
		deep: true,
		immediate: true
	}
)

// 总体积V
watch(
	() => dataForm.smallVOList,
	val => {
		if (Array.isArray(val)) {
			dataForm.tiji = val.reduce((total, item) => {
				return total + parseFloat(item.collectTiji || 0)
			}, 0)
		} else {
			dataForm.tiji = 0
		}
	},
	{
		deep: true,
		immediate: true
	}
)

//体积重(Kg)
watch(
	() => dataForm.smallVOList,
	val => {
		if (Array.isArray(val)) {
			dataForm.tijiWeight = val.reduce((total, item) => {
				return total + parseFloat(item.collectTijiWeight || 0)
			}, 0)
		} else {
			dataForm.tijiWeight = 0
		}
	},
	{
		deep: true,
		immediate: true
	}
)

const collectTJi = (row: {
	collectLength: number
	collectKuan: number
	collectHeight: number
	collectTiji: string | number
	collectTijiWeight: string | number
}) => {
	console.log(row, '计算体积重')
	if (!isNaN(row.collectLength) && !isNaN(row.collectKuan) && !isNaN(row.collectHeight)) {
		const volume = ((row.collectLength * row.collectKuan * row.collectHeight) / 1000000).toFixed(3)
		const weight = ((row.collectLength * row.collectKuan * row.collectHeight) / 6000).toFixed(3)
		row.collectTiji = volume
		row.collectTijiWeight = weight
	} else {
		row.collectTiji = 0.0
		row.collectTijiWeight = 0.0
	}
}
// 体积和
getId()

defineExpose({
	init
})

//数据列表
const countryList = ref<ElSelectOption[]>([])
const arrivalOptions = ref<ElSelectOption[]>([])
const paysOptions = ref<ElSelectOption[]>([])
const getLocation = async () => {
	try {
		const res = await getExpressRelatedData()

		if (res.code === 0) {
			const data = res.data
			countryList.value = data.countryList
			businessTypeList.value = data.businessTypeList
			arrivalOptions.value = data.arrivalOptionsList
			paysOptions.value = data.paymentList
			chargedOptions.value = data.chargedOptionsList.map(item => ({
				...item,
				value: parseInt(item.value)
			}))
			collectTypeOptions.value = data.collectTypeOptionsList.map(item => ({
				...item,
				value: parseInt(item.value)
			}))

			
			cargoOptionsCanUpdate.value = data.cargoOptionsList
				.filter(item => item.value === 1 || item.value === 0).map(
					item => (
								{
									...item,
									value: parseInt(item.value)
								}	
							)
				)
			
			for( let item of data.cargoOptionsList ){
				collectStateArr[item.value] = item.label;
			}

			console.log('getExpressRelatedData', data)
		} else {
			console.error('Error in response code:', res.message)
		}
	} catch (e) {
		console.log(e, '失败')
	}
}
getLocation()
</script>

<style scoped>
.form-row {
	margin-bottom: 20px;
	/* Adjust the margin as needed */
}

.flex-container {
	display: flex;
	align-items: center;
	/* 垂直居中 */
	margin-left: 5px;
}

.input-width {
	width: 200px;
}

.label-style {
	width: 250px;
}

.input-nub {
	width: 20%;
}
</style>
